package com.example.tourstor;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.tourstor.database.DBManager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

public class MerchantActivity extends AppCompatActivity {


    private ImageView back;
    private ImageView share;
    private TextView m_name;
    private TextView m_score;
    private TextView m_place;
    private TextView m_onen_time;
    private TextView m_close_time;
    private ListView m_product;
    private ListView m_comment;

    ListAdapter listAdapter;
    Thread thread1, thread2, thread3;
    private DBManager dbManager = DBManager.createInstance();

    private Intent intent;
    private Handler handler;

    private static final String TAG = "MerchantActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant);

        back = findViewById(R.id.activity_merchant_back);
        share = findViewById(R.id.activity_merchant_share);

        m_name = findViewById(R.id.activity_merchant_Mname);
        m_score = findViewById(R.id.activity_merchant_Mscore);
        m_place = findViewById(R.id.activity_merchant_Mplace);
        m_onen_time = findViewById(R.id.activity_merchant_Mopen_time);
        m_close_time = findViewById(R.id.activity_merchant_Mclose_time);

        m_product = findViewById(R.id.activity_merchant_product);
        m_comment = findViewById(R.id.activity_merchant_comment);

        intent = getIntent();
        Log.i(TAG, "onCreate: Mno = " + intent.getIntExtra("Mno", 0));

        initMerchantInfo();
        initProductList();
        initCommentList();

        m_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView merchantNo = view.findViewById(R.id.productItem_Pno);
                int n = Integer.valueOf(merchantNo.getText().toString());
                Log.i(TAG, "onItemClick: Pno = " + n);
                Intent intent = new Intent(MerchantActivity.this, ProductActivity.class);
                intent.putExtra("Pno", n);
                startActivity(intent);
            }
        });

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1){
                    Bundle bundle = (Bundle)msg.obj;
                    m_name.setText(bundle.getString("Mname"));
                    m_score.setText(bundle.getDouble("Mscore") + "分");
                    m_place.setText(bundle.getString("Mplace"));
                    m_onen_time.setText(bundle.getString("Mopentime"));
                    m_close_time.setText(bundle.getString("Mclosetime"));


                }
                else if(msg.what == 2)
                {
                    ArrayList list = (ArrayList) msg.obj;
                    if(list != null){
                        listAdapter = new SimpleAdapter(MerchantActivity.this, list, R.layout.item_product,
                                new String[]{"Mno", "Pno", "Pname", "Pprice", "Poriginal_price", "Psales", "Pscore"},
                                new int[]{R.id.productItem_Mno, R.id.productItem_Pno, R.id.productItem_name,
                                        R.id.productItem_price, R.id.productItem_original_price, R.id.productItem_sales,
                                        R.id.productItem_score});
                        m_product.setAdapter(listAdapter);
                        setListViewHeightBasedOnChildren(m_product);
                    }



                }
                else if(msg.what == 3)
                {
                    ArrayList list = (ArrayList) msg.obj;
                    if (list != null) {
                        listAdapter = new SimpleAdapter(MerchantActivity.this, list, R.layout.item_comment,
                                new String[]{"Cno", "Pno", "Uno", "Uname", "Ctxt", "Cscore", "Ctime"},
                                new int[]{R.id.commentItem_Cno, R.id.commentItem_Pno, R.id.commentItem_Uno,
                                        R.id.commentItem_Uname, R.id.commentItem_Ctxt,
                                        R.id.commentItem_score, R.id.merchantItem_Ctime});
                        m_comment.setAdapter(listAdapter);
                        setListViewHeightBasedOnChildren(m_comment);
                    }


                }



            }
        };



        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    private void initMerchantInfo(){

        Log.i(TAG, "initMerchantInfo: ");
        thread1 = new Thread(new Runnable() {
            @Override
            public void run() {

                synchronized(this){
                    dbManager.connectDB();
                    Bundle bundle = new Bundle();
                    String sql = "select * from merchant where Mno = " + intent.getIntExtra("Mno", 0);
                    try {
                        ResultSet rs = dbManager.stmt.executeQuery(sql);
                        rs.next();
                        bundle.putInt("Mno", rs.getInt("Mno"));
                        bundle.putString("Mname", rs.getString("Mname"));
                        bundle.putString("Mplace", rs.getString("Mplace"));
                        bundle.putString("Mtel", rs.getString("Mtel"));
                        bundle.putString("Mmobile", rs.getString("Mmobile"));
                        bundle.putString("Mclass", rs.getString("Mclass"));
                        bundle.putString("Mclosetime", rs.getString("Mclosetime"));
                        bundle.putString("Mopentime", rs.getString("Mopentime"));
                        bundle.putDouble("Mscore", rs.getDouble("Mscore"));
                        Log.i(TAG, "getMerchantItem: Mno = " + rs.getInt("Mno"));
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    dbManager.closeDB();
                    Message msg = handler.obtainMessage(1);
                    msg.what = 1;
                    msg.obj = bundle;
                    handler.sendMessage(msg);
                }

            }
        });
        thread1.start();
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }



    private void initProductList(){

        Log.i(TAG, "initProductList: ");
        thread2 = new Thread(new Runnable() {
            @Override
            public void run() {

                synchronized(this) {

                    try {
                        thread1.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                    String sql = "select * from product where Mno = " + intent.getIntExtra("Mno", 0);
                    dbManager.connectDB();
                    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
                    try {
                        ResultSet rs = dbManager.stmt.executeQuery(sql);
                        while (rs.next()) {
                            //"Mno", "Pno", "Pname", "Pprice", "Poriginal_price", "Psales", "Pscore"
                            HashMap<String, String> post = new HashMap<String, String>();
                            post.put("Pno", rs.getString("Pno"));
                            post.put("Mno", rs.getString("Mno"));
                            post.put("Pname", rs.getString("Pname"));
                            post.put("Pprice", rs.getString("Pprice"));
                            post.put("Psales", rs.getString("Psales"));
                            post.put("Pscore", rs.getString("Pscore"));
                            post.put("Poriginal_price", rs.getString("Poriginal_price"));
                            list.add(post);
                            Log.i(TAG, "getMerchantInfo: Pno = " + rs.getString("Pno"));
                        }
                        rs.close();
                        Log.i(TAG, "getProductInfo: Select successful");
                    } catch (SQLException e) {
                        Log.i(TAG, "getProductInfo: SQLException");
                        e.printStackTrace();
                    }
                    dbManager.closeDB();

                    Message msg = handler.obtainMessage(2);
                    msg.what = 2;
                    msg.obj = list;
                    handler.sendMessage(msg);
                }

            }
        });
        thread2.start();

    }

    private void initCommentList(){

        Log.i(TAG, "initCommentList: ");
        thread3 = new Thread(new Runnable() {
            @Override
            public void run() {

                synchronized(this) {

                    try {
                        thread2.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    String sql = "select * from User, comment,product where `User`.U_id = `comment`.Uno and product.Pno = `comment`.Pno and product.Mno = "
                            + intent.getIntExtra("Mno", 0) + " order by Ctime desc" ;
                    dbManager.connectDB();
                    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
                    try {
                        ResultSet rs = dbManager.stmt.executeQuery(sql);
                        while (rs.next()) {

                            HashMap<String, String> post = new HashMap<String, String>();
                            post.put("Cno", rs.getString("Cno"));
                            post.put("Pno", rs.getString("Pno"));
                            post.put("Uno", rs.getString("Uno"));
                            post.put("Uname", rs.getString("u_name"));
                            post.put("Ctxt", rs.getString("Ctxt"));
                            post.put("Ctime", rs.getString("Ctime"));
                            post.put("Cscore", rs.getString("Cscore"));
                            list.add(post);
                            Log.i(TAG, "getMerchantInfo: Cno = " + rs.getString("Cno"));

                        }
                        rs.close();
                        Log.i(TAG, "getCommentInfo : success");
                    } catch (SQLException e) {
                        Log.i(TAG, "getPostList: SQLException");
                        e.printStackTrace();
                    }
                    dbManager.closeDB();

                    Message msg = handler.obtainMessage(3);
                    msg.what = 3;
                    msg.obj = list;
                    handler.sendMessage(msg);
                }

            }
        });
        thread3.start();
    }

    /*
     * 解决多个listView滑动冲突的问题
     * 在scollview中嵌套layout 这样才能插入组件
     * 使用scollview为界面插入滚动条
     *
     * 解决思路为固定listview的高度
     * */
    public void setListViewHeightBasedOnChildren(ListView listView){
        BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);  //在还没有构建View 之前无法取得View的度宽。 在此之前我们必须选 measure 一下.
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // params.height += 5;// if without this statement,the listview will be
        // a
        // little short
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);

    }



}
